package dockerinfo

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func GetDockerList() (cs ContainerData) {

	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})

	for _, container := range containers {
		stats, err := cli.ContainerStatsOneShot(ctx, container.ID)
		if err != nil {
			panic(err)
		}
		bodyBytes, err := ioutil.ReadAll(stats.Body)
		if err != nil {
			log.Fatal(err)
		}
		bodyString := string(bodyBytes)
		var cst ContainerStats
		err = json.Unmarshal([]byte(bodyString), &cst)
		if err != nil {
			log.Fatal(err)
		}

		cI := containerInfo{cst.Name, cst.ID, fmt.Sprint(cst.MemoryStats.Usage/1024/1024) + "MB"}
		cs.ContainerInfo = append(cs.ContainerInfo, cI)

	}
	return cs
}
